package com.cm.figure.utility;

import io.jsonwebtoken.*;

import java.util.Date;

/**
 * ClassName:Token
 * Package:com.cm.figure.utility
 * Description:
 *
 * @Date:2021/8/14 21:37
 * @com.chuangmei
 */
public class Token {

    private static int time = 1000*60*60*24;
    private static String signature = "admin";

    public static void main(String[] args) {
        System.out.println(getToken("Renyi", 001));


        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IlJlbnlpIiwidXNlcmlkIjoxLCJzdWIiOiJmaWd1cmUiLCJleHAiOjE2MjkwMzU0MTZ9.auww6S57IBIXhAMl1-XuNis5t0sT12qOfXax8c-ksnQ";
        Claims claims = parse(token);
        System.out.println(claims.get("username"));
        System.out.println(claims.get("userid"));
        System.out.println(claims.getId());
        System.out.println(claims.getExpiration());
        System.out.println(claims.getSubject());
    }

    public static String getToken(String username, int userid) {
        JwtBuilder jwtBuilder = Jwts.builder();

        return jwtBuilder
                // Header
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                // payload
                .claim("username",username)
                .claim("userid",userid)
                .setSubject("figure")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                // signature
                .signWith(SignatureAlgorithm.HS256,signature)
                // 拼接
                .compact();

    }


    public static Claims parse(String token) {
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);
        return claimsJws.getBody();
    }
}
